﻿using System.IO;
using Newtonsoft.Json;
using ShortcutToolbox.Core;

namespace ShortcutToolbox.Model
{
    class Configuration
    {
        static Configuration _instance;
        static object _locker = new object();

        public static Configuration Current
        {
            get
            {
                if (_instance == null)
                {
                    lock (_locker)
                    {
                        if (_instance == null)
                        {
                            string file = Utils.GetAppDataFilePath("config.json");
                            if (File.Exists(file))
                                _instance = Configuration.Load(Utils.GetAppDataFilePath("config.json"));
                            else
                            {
                                _instance = new Configuration();
                                _instance._FileName = file;
                                _instance.IsDefault = true;
                                _instance.Language = I18N.Current.name;
                                _instance.Save();
                            }
                        }
                    }
                }
                return _instance;
            }
        }

        [JsonIgnore]
        protected string _FileName { get; set; }

        [JsonIgnore]
        public bool IsDefault { get; private set; }

        public string Language { get; set; }

        public bool CheckUpdateOnStart { get; set; }

        public void Reload()
        {
            Configuration config = Load(_FileName);
            Language = config.Language;
            CheckUpdateOnStart = config.CheckUpdateOnStart;
        }

        public void Save()
        {
            Save(_FileName, this);
        }

        public static Configuration Load(string filename)
        {
            string json = File.ReadAllText(filename);
            Configuration config = JsonConvert.DeserializeObject<Configuration>(json);
            config._FileName = filename;
            return config;
        }

        public static void Save(string filename, Configuration config)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Formatting = Formatting.Indented;
            string json = JsonConvert.SerializeObject(config);
            string directory = Path.GetDirectoryName(filename);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            File.WriteAllText(filename, json);
        }
    }

}
